package com.qianbao.qianbaobusiness.ui.home;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.androidbase.base.BaseApplication;
import com.androidbase.utils.RxUtils;
import com.androidbase.utils.ToastUtils;
import com.baseandroid.config.Global;
import com.baseandroid.event.LocationResultEvent;
import com.baseandroid.event.LoginInvalideEvent;
import com.baseandroid.event.UnReadMsgEvent;
import com.baseandroid.gaode.GaoDeMap;
import com.baseandroid.jpush.JPushBizutils;
import com.baseandroid.jpush.JPushService;
import com.baseandroid.mvp.BaseMvpActivity;
import com.baseandroid.push.PushDoneService;
import com.baseandroid.retrofit.RxObserver;
import com.jaeger.library.StatusBarUtil;
import com.qianbao.qianbaobusiness.BuildConfig;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.help.PermissionDialogHelper;
import com.qianbao.qianbaobusiness.json.ChannelBean;
import com.qianbao.qianbaobusiness.json.UnPayinfoParentBean;
import com.qianbao.qianbaobusiness.json.UserPermession;
import com.qianbao.qianbaobusiness.ui.borrow.BorrowFragment;
import com.qianbao.qianbaobusiness.ui.cashier.CashierFragment;
import com.qianbao.qianbaobusiness.ui.deposit.DepositToH5Activity;
import com.qianbao.qianbaobusiness.ui.login.LoginActivity;
import com.qianbao.qianbaobusiness.ui.mine.MineFragment;
import com.qianbao.qianbaobusiness.ui.support.SupportFragment;
import com.qianbao.qianbaobusiness.ui.webview.LoanWebviewActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.stat.StatService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import exocr.exocrengine.DictManager;

public class HomeActivity extends BaseMvpActivity<HomeView, HomePresenter> implements HomeView {

    @BindView(R.id.content)
    FrameLayout mContent;
    @BindView(R.id.rb_cashier)
    RadioButton mRbCashier;
    @BindView(R.id.rb_loan)
    RadioButton mRbLoan;
    @BindView(R.id.rg)
    RadioGroup  mRg;

    CashierFragment mCashierFragment;
    SupportFragment mSupportFragment;
    BorrowFragment  mLoanFragment;
    MineFragment    mMineFragment;
    private long firstTime = 0;
    FragmentTransaction ft;
    private RadioButton mPreSelected;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        StatusBarUtil.setTranslucentForImageViewInFragment(HomeActivity.this, 0, null);
        if (Global.getShopListInfo().loanInfo != null && Global.getShopListInfo().loanInfo
                                                                 .isEnable() && Global.getShopListInfo().getLoanMerchantInfo() != null) {
            for (UserPermession userPermession : Global.getShopListInfo()
                                                         .getLoanMerchantInfo().menuList) {
                if (TextUtils.equals("M100801", userPermession.menuCode)) {
                    mRbLoan.setVisibility(View.VISIBLE);
                    break;
                }
            }
        }
        if (Global.getShopListInfo().merchantList == null || Global.getShopListInfo().merchantList
                                                                     .size() == 0) {
            mRbLoan.setVisibility(View.GONE);
        }
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
        int id = 0;
        if (savedInstanceState != null) {
            id = savedInstanceState.getInt("rb_checked", 0);
        }
        if (id == 0) {
            showFragment(R.id.rb_cashier);
        } else {
            showFragment(id);
        }
        EventBus.getDefault().register(this);
        /*--高德开始定位--*/
        GaoDeMap.getInstance().startMap();
        /*--极光启动前台服务--*/
        startService(new Intent(HomeActivity.this, JPushService.class));
        /*--启动推送后台服务--*/
        startService(new Intent(HomeActivity.this, PushDoneService.class));
        /* ORC识别初始化字典 */
        DictManager.InitDict(this);
        /*--请求广告位--*/
        getPresenter().getAppAdvertImg();
    }

    @OnClick({R.id.rb_cashier, R.id.rb_support, R.id.rb_loan, R.id.rb_mine})
    public void onViewClicked(View view) {
        if (view != mRbLoan) {
            mPreSelected = (RadioButton) view;
        } else {
            if (mPreSelected == null) {
                mPreSelected = mRbCashier;
            }
            mPreSelected.setChecked(true);
        }
        showFragment(view.getId());
    }

    public void showFragment(int index) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        ft = fragmentManager.beginTransaction();
        switch (index) {
            case R.id.rb_cashier:
                hideFragment(ft);
                if (mCashierFragment != null) {
                    ft.show(mCashierFragment);
                } else {
                    mCashierFragment = new CashierFragment();
                    ft.add(R.id.content, mCashierFragment);
                }
                ft.commitAllowingStateLoss();
                break;
            case R.id.rb_support:
                hideFragment(ft);
                if (mSupportFragment != null) {
                    ft.show(mSupportFragment);
                } else {
                    mSupportFragment = new SupportFragment();
                    ft.add(R.id.content, mSupportFragment);
                }
                ft.commitAllowingStateLoss();
                break;
            case R.id.rb_loan:
                if (Global.mbLocSuccess) {
                    LoanWebviewActivity.gotoLoanWebView(this, Global.getUserInfoBean()
                                                                      .getLoanAccessToken(), "loan_apply", "商户贷", "cashier");
                    if (!BuildConfig.DEBUG) {
                        StatService.trackCustomEvent(Global.getContext(), "3_0_home_zcd");
                    }
                } else {
                    new RxPermissions(this).request(Manifest.permission.ACCESS_FINE_LOCATION)
                            .compose(RxUtils.<Boolean>applySchedulersLifeCycle(getMvpView()))
                            .subscribe(new RxObserver<Boolean>() {
                                @Override
                                public void onNext(Boolean granted) {
                                    if (granted) {
                                        GaoDeMap.getInstance().startMap();
                                    } else {
                                        new PermissionDialogHelper(HomeActivity.this).setMsg("没有定位权限，请去设置页添加相应权限").show();
                                    }
                                }
                            });
                }
                break;
            case R.id.rb_mine:
                hideFragment(ft);
                if (mMineFragment != null) {
                    ft.show(mMineFragment);
                } else {
                    mMineFragment = new MineFragment();
                    ft.add(R.id.content, mMineFragment);
                }
                if (!BuildConfig.DEBUG) {
                    StatService.trackCustomEvent(Global.getContext(), "3_0_mine");
                }
                ft.commitAllowingStateLoss();
                break;
            default:
                break;
        }
    }

    @Override
    public void onAttachFragment(android.support.v4.app.Fragment fragment) {
        super.onAttachFragment(fragment);
        if (mCashierFragment == null && fragment instanceof CashierFragment) {
            mCashierFragment = (CashierFragment) fragment;
            getSupportFragmentManager().beginTransaction()
                    .hide(mCashierFragment)
                    .commit();
        } else if (mSupportFragment == null && fragment instanceof SupportFragment) {
            mSupportFragment = (SupportFragment) fragment;
            getSupportFragmentManager().beginTransaction()
                    .hide(mSupportFragment)
                    .commit();
        } else if (mLoanFragment == null && fragment instanceof BorrowFragment) {
            mLoanFragment = (BorrowFragment) fragment;
            getSupportFragmentManager().beginTransaction().hide(mLoanFragment).commit();
        } else if (mMineFragment == null && fragment instanceof MineFragment) {
            mMineFragment = (MineFragment) fragment;
            getSupportFragmentManager().beginTransaction().hide(mMineFragment).commit();
        }
    }

    private void hideFragment(android.support.v4.app.FragmentTransaction ft) {
        if (mCashierFragment != null) {
            ft.hide(mCashierFragment);
        }
        if (mLoanFragment != null) {
            ft.hide(mLoanFragment);
        }
        if (mSupportFragment != null) {
            ft.hide(mSupportFragment);
        }
        if (mMineFragment != null) {
            ft.hide(mMineFragment);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginInvalideEvent event) {
        /*--清空所有页面--*/
        BaseApplication.getAppManager().finishAllActivity();
        Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        Global.loginOutclear();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LocationResultEvent event) {
        if (event.isMbResult()) {
            Global.mbLocSuccess = true;
        } else {
            Global.mbLocSuccess = false;
        }
        getPresenter().getAppPushconfig();
        getPresenter().getAppAlphaZone();
    }


    @Override
    public void onAppPushConfig(boolean state, ChannelBean channelBean) {
        if (state) {
            setPushChannel(channelBean.channel);
        } else {
            if (TextUtils.isEmpty(Global.getPushConfig())) {
                setPushChannel("0");
            } else {
                setPushChannel(Global.getPushConfig());
            }
        }
    }

    @Override
    public void AlphaZone() {
    }

    @Override
    public void hasUnPay(UnPayinfoParentBean result) {
        if (result.getUnPayinfo() != null && result.getUnPayinfo().size() > 0) {
            startActivity(new Intent(this, DepositToH5Activity.class));
        }
    }

    private void setPushChannel(String channel) {
        if (!TextUtils.isEmpty(channel) && channel.equals("1")) {
            JPushBizutils.stopJPush("");
            PushServiceFactory.getCloudPushService()
                    .turnOnPushChannel(new CommonCallback() {
                        @Override
                        public void onSuccess(String s) {

                        }

                        @Override
                        public void onFailed(String s, String s1) {

                        }
                    });
        } else {
            JPushBizutils.initJPush();
            PushServiceFactory.getCloudPushService()
                    .turnOffPushChannel(new CommonCallback() {
                        @Override
                        public void onSuccess(String s) {

                        }

                        @Override
                        public void onFailed(String s, String s1) {

                        }
                    });
        }
        Global.setPushConfig(channel);

        getPresenter().updataAppPushconfig(channel);
        //        String afterId;
        //        if (Global.hasUserId(Global.getUserInfoBean().getUser().getUserNo())) {
        //            afterId = "0";
        //        } else {
        //            afterId = Global.getAfterId(Global.getUserInfoBean().getUser().getUserNo());
        //        }
        if (Global.getLoginCurrently()) {
            getPresenter().getMerchantPaymentInfo("0");
            Global.setLoginCurrently(false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(UnReadMsgEvent event) {
        if (event.isShowIcon()) {
            mRbCashier.setCompoundDrawablesRelativeWithIntrinsicBounds(null, ContextCompat
                                                                                     .getDrawable(this, R.drawable.selector_icon_cashier_alert), null, null);
        } else {
            mRbCashier.setCompoundDrawablesRelativeWithIntrinsicBounds(null, ContextCompat
                                                                                     .getDrawable(this, R.drawable.selector_icon_cashier), null, null);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                ToastUtils.showLongToast("再按一次退出钱包商家");
                firstTime = secondTime;
                return true;
            } else {
                //执行返回桌面
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DictManager.FinishDict();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("rb_checked", mRg.getCheckedRadioButtonId());
        super.onSaveInstanceState(outState);
    }
}
